package messages.observer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import state.Globals;
import state.group.GroupDispatcherState;
import messages.BaseMessage;
import messages.MessageType;

public class CurrentStateMessage extends BaseMessage {
    
    byte[] data = null;

    public CurrentStateMessage(byte[] data)
    {
        super(data);
        this.data = data;
    }
    
    public CurrentStateMessage(GroupDispatcherState state) throws IOException
    {
        super(null);
        
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
        byteOutput.write(getMessageType().getIdentifier());
        
        ObjectOutputStream output = new ObjectOutputStream(byteOutput);
        
        output.writeObject(state);
        
        data = byteOutput.toByteArray();
        
    }

    @Override
    public byte[] toByteArray()
    {
        return data;
    }
    
    public GroupDispatcherState getDispatcherState() throws IOException
    {
        ByteArrayInputStream byteInput = new ByteArrayInputStream(data);
        //get rid of the identifier
        byteInput.read();
        
        ObjectInputStream objectStream = new ObjectInputStream(byteInput);
        Object result;
        try
        {
            result = objectStream.readObject();
        }
        catch (ClassNotFoundException e)
        {
            Globals.getLogger().error("Could not identify class by serializing!", e);
            return null;
        }
        
        if (result instanceof GroupDispatcherState)
        {
            return (GroupDispatcherState) result;
        }
        
        return null;
    }

    @Override
    public MessageType getMessageType()
    {
        return MessageType.CurrentStateMessage;
    }

    @Override
    public int getMessageSize()
    {
        return -1;
    }

}
